package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"strconv"
	"time"
)

// 1获得入社申请
func GetClubApply(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	var applies []model.Apply
	result := DB.Where("approver1 = ? AND kind = ? and approval_state!=?", account, 0, 8).Find(&applies)

	if result.Error != nil {
		if gorm.IsRecordNotFoundError(result.Error) {
			response.Response(ctx, http.StatusOK, 200, nil, "暂时没有入社申请：")
			return
		} else {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询入社申请错误: %v", result.Error))
			return
		}
	}

	var detailedApplies []model.JoinClubApply
	for _, apply := range applies {
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}

		var clubPermission model.ClubPermission
		if err := DB.Where("id = ?", apply.Apply_ID).First(&clubPermission).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询入社分表失败!")
			return
		}

		var club model.Club
		if err := DB.Where("id = ?", clubPermission.Cid).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}
		var file model.AllFile
		if err := DB.Table("all_file").Where("id = ?", clubPermission.PFile).First(&file).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询文件信息失败!")
			return
		}

		detailedApply := model.JoinClubApply{
			ID:            apply.ID,
			ApplyID:       apply.Apply_ID,
			ApplyTime:     apply.ApplyTime,
			UID:           apply.UserID,
			UName:         user.Uname,
			CID:           club.Cid,
			CName:         club.Cname,
			Reason:        clubPermission.PReason,
			File:          file,
			ApprovalState: apply.Approval_State,
		}

		detailedApplies = append(detailedApplies, detailedApply)
	}

	response.Success(ctx, gin.H{"clubs": detailedApplies}, "入社申请获取成功!")
}

// 2获得加入活动申请
func GetActivityApply(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	var applies []model.Apply
	result := DB.Where("approver1 = ? AND kind = ? and approval_state!=?", account, 1, 8).Find(&applies)
	if result.Error != nil {
		if gorm.IsRecordNotFoundError(result.Error) {
			response.Response(ctx, http.StatusOK, 200, nil, "暂时没有活动申请：")
			return
		} else {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询活动申请错误: %v", result.Error))
			return
		}
	}
	var detailedApplies []model.JoinActivityApply
	for _, apply := range applies {
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}
		//获得AID
		var activityApply model.ActivityApply
		if err := DB.Where("id = ?", apply.Apply_ID).First(&activityApply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询参加活动分表失败!")
			return
		}
		//为了获得活动标题
		var activity model.Activity
		if err := DB.Where("id = ?", activityApply.Aid).First(&activity).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询活动信息失败!")
			return
		}
		//获得社团名字
		var club model.Club
		if err := DB.Where("id = ?", activity.Cid).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}
		//组装
		detailedApply := model.JoinActivityApply{
			ID:            apply.ID,
			ApplyID:       apply.Apply_ID,
			ApplyTime:     apply.ApplyTime,
			UID:           apply.UserID,
			UName:         user.Uname,
			AID:           activity.Aid,
			AName:         activity.ATitle,
			CID:           club.Cid,
			CName:         club.Cname,
			ApprovalState: apply.Approval_State,
		}

		detailedApplies = append(detailedApplies, detailedApply)
	}

	response.Success(ctx, gin.H{"activities": detailedApplies}, "加入活动申请获取成功!")
}

// 3获得年检申请
func GetAS(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	//fmt.Println("account", account)
	permisssion := ctx.Query("permission")
	var applies []model.Apply
	switch permisssion {
	case "2":
		result := DB.Where("approver2 = ? AND kind = ? and approval_state!=?", account, 2, 8).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有年检申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询年检申请错误: %v", result.Error))
				return
			}
		}
	case "3":
		result := DB.Where("approver3 = ? AND kind = ? AND approval_state IN (?)", account, 2, []int{3, 5, 6}).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有年检申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询年检申请错误: %v", result.Error))
				return
			}
		}
	}

	var detailedApplies []model.ASApplies
	for _, apply := range applies {
		fmt.Println("apply", apply)
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}

		var asApply model.Apply_AS
		if err := DB.Where("id = ?", apply.Apply_ID).First(&asApply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询年检分表失败!")
			return
		}
		var issueAS model.IssueAS
		if err := DB.Table("issue_as").Where("CPID = ?", asApply.CPID).First(&issueAS).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询年检发布表失败!")
			return
		}
		var club model.Club
		if err := DB.Where("id = ?", asApply.CID).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}
		var file model.AllFile
		if err := DB.Table("all_file").Where("id = ?", asApply.File).First(&file).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询文件信息失败!")
			return
		}
		if issueAS.State == 1 {
			detailedApply := model.ASApplies{
				ID:            apply.ID,
				ApplyID:       apply.Apply_ID,
				ApplyTime:     apply.ApplyTime,
				UID:           apply.UserID,
				UName:         user.Uname,
				CName:         club.Cname,
				File:          file,
				CPID:          asApply.CPID,
				CPName:        issueAS.CPName,
				ApprovalState: apply.Approval_State,
			}
			detailedApplies = append(detailedApplies, detailedApply)
		}
	}

	response.Success(ctx, gin.H{"asApplies": detailedApplies}, "年检申请获取成功!")
}

// 4获得评优申请
func GetCE(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	permisssion := ctx.Query("permission")
	var applies []model.Apply
	switch permisssion {
	case "2":
		result := DB.Where("approver2 = ? AND kind = ? and approval_state!=?", account, 3, 8).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有评优申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询评优申请错误: %v", result.Error))
				return
			}
		}
	case "3":
		result := DB.Where("approver3 = ? AND kind = ? AND approval_state IN (?)", account, 3, []int{3, 5, 6}).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有评优申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询评优申请错误: %v", result.Error))
				return
			}
		}
	}

	var detailedApplies []model.CEApplies
	for _, apply := range applies {
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}

		var ceApply model.Apply_CE
		if err := DB.Table("apply_ce").Where("id = ?", apply.Apply_ID).First(&ceApply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询评优分表失败!")
			return
		}
		var issueCE model.IssueCE
		if err := DB.Table("issue_ce").Where("CEID = ?", ceApply.CEID).First(&issueCE).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询评优发布表失败!")
			return
		}
		var club model.Club
		if err := DB.Where("id = ?", ceApply.CID).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}
		var file model.AllFile
		if err := DB.Table("all_file").Where("id = ?", ceApply.File).First(&file).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询文件信息失败!")
			return
		}
		if issueCE.State == 1 {
			detailedApply := model.CEApplies{
				ID:            apply.ID,
				ApplyID:       apply.Apply_ID,
				ApplyTime:     apply.ApplyTime,
				UID:           apply.UserID,
				UName:         user.Uname,
				CName:         club.Cname,
				File:          file,
				CEID:          ceApply.CEID,
				CEName:        issueCE.CEName,
				ApprovalState: apply.Approval_State,
			}

			detailedApplies = append(detailedApplies, detailedApply)
		}
	}

	response.Success(ctx, gin.H{"ceApplies": detailedApplies}, "评优申请获取成功!")
}

// 5创建社团申请
func GetCreateClub(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	permisssion := ctx.Query("permission")
	var applies []model.Apply
	switch permisssion {
	case "2":
		result := DB.Where("approver2 = ? AND kind = ? and approval_state!=?", account, 4, 8).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有创社申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询创社申请错误: %v", result.Error))
				return
			}
		}
	case "3":
		result := DB.Where("approver3 = ? AND kind = ? AND approval_state IN (?)", account, 4, []int{3, 5, 6}).Find(&applies)
		if result.Error != nil {
			if gorm.IsRecordNotFoundError(result.Error) {
				response.Response(ctx, http.StatusOK, 200, nil, "暂时没有创社申请：")
				return
			} else {
				response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询创社申请错误: %v", result.Error))
				return
			}
		}
	}

	var detailedApplies []model.CreateClubApply
	for _, apply := range applies {
		var ccApply model.Apply_CreateClub
		fmt.Println("apply.Apply_ID", apply.Apply_ID)
		if err := DB.Table("apply_createclub").Where("id = ?", apply.Apply_ID).First(&ccApply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查创社优分表失败!")
			return
		}
		fmt.Println("ccApply.Cid", ccApply.Cid)
		var club model.Club
		if err := DB.Where("id = ?", ccApply.Cid).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询创社申请错误: %v", ccApply.Cid))
			return
		}
		var file model.AllFile
		if err := DB.Table("all_file").Where("id = ?", ccApply.File).First(&file).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询文件信息失败!")
			return
		}
		detailedApply := model.CreateClubApply{
			ID:                apply.ID,
			ApplyID:           apply.Apply_ID,
			ApplyTime:         apply.ApplyTime,
			LeaderID:          apply.UserID,
			LeaderName:        club.LeaderName,
			Mailbox:           club.Mailbox,
			Phone:             club.Phone,
			CID:               club.Cid,
			CName:             club.Cname,
			File:              file,
			ApprovalState:     apply.Approval_State,
			Campus:            club.Address,
			Type:              club.Type,
			AIM:               club.Aim,
			UNIT:              club.Unit,
			TeacherID:         club.TeacherID,
			TeacherName:       club.TeacherName,
			TeacherPhone:      club.TeacherPhone,
			AdminTeacherID:    club.AdminTeacherID,
			AdminTeacherName:  club.AdminTeacherName,
			AdminTeacherPhone: club.AdminTeacherPhone,
			Introduction:      club.Introduction,
		}

		detailedApplies = append(detailedApplies, detailedApply)
	}

	response.Success(ctx, gin.H{"createclubs": detailedApplies}, "创社申请获取成功!")
}

// 6举办活动申请
func GetCreateActivity(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	permisssion := ctx.Query("permission")
	var applies []model.Apply
	switch permisssion {
	case "2":
		result := DB.Where("approver2 = ? AND kind = ? and approval_state!=?", account, 5, 8).Find(&applies)
		if gorm.IsRecordNotFoundError(result.Error) {
			response.Response(ctx, http.StatusOK, 200, nil, "暂时没有举办活动申请：")
			return
		} else {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询举办活动申请错误: %v", result.Error))
			return
		}
	case "3":
		result := DB.Where("approver3 = ? AND kind = ? AND approval_state IN (?)", account, 5, []int{3, 5, 6}).Find(&applies)
		if gorm.IsRecordNotFoundError(result.Error) {
			response.Response(ctx, http.StatusOK, 200, nil, "暂时没有举办活动申请：")
			return
		} else {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询举办活动申请错误: %v", result.Error))
			return
		}
	}

	var detailedApplies []model.CreateActivityApply
	for _, apply := range applies {
		fmt.Println("apply", apply)
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}

		var caApply model.ActivityCreate
		if err := DB.Where("id = ?", apply.Apply_ID).First(&caApply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查创举办活动分表失败!")
			return
		}
		//为了获得活动标题
		var activity model.Activity
		if err := DB.Where("id = ?", caApply.Aid).First(&activity).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询活动信息失败!")
			return
		}
		var club model.Club
		if err := DB.Where("id = ?", activity.Cid).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}
		var file model.AllFile
		if err := DB.Table("all_file").Where("id = ?", caApply.File).First(&file).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询文件信息失败!")
			return
		}
		detailedApply := model.CreateActivityApply{
			ID:            apply.ID,
			ApplyID:       apply.Apply_ID,
			ApplyTime:     apply.ApplyTime,
			UID:           apply.UserID,
			UName:         user.Uname,
			AID:           activity.Aid,
			AName:         activity.ATitle,
			CID:           club.Cid,
			CName:         club.Cname,
			File:          file,
			ApprovalState: apply.Approval_State,
			Place:         activity.Place,
			Campus:        activity.Campus,
			Type:          activity.Type,
			ApplyStime:    activity.StartTime,
			ApplyEtime:    activity.EndTime,
			Stime:         activity.Stime,
			Etime:         activity.Etime,
			Permit:        activity.Permission,
			Content:       activity.Content,
			Requirment:    activity.Requirement,
		}

		detailedApplies = append(detailedApplies, detailedApply)
	}

	response.Success(ctx, gin.H{"createactivities": detailedApplies}, "举办活动申请获取成功!")
}

// 6获得退社申请
func GetQuitClubApply(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	var applies []model.Apply
	result := DB.Where("approver1 = ? AND kind = ? and approval_state!=?", account, 6, 8).Find(&applies)
	if gorm.IsRecordNotFoundError(result.Error) {
		response.Response(ctx, http.StatusOK, 200, nil, "暂时没有退社申请：")
		return
	} else {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, fmt.Sprintf("查询退社申请错误: %v", result.Error))
		return
	}

	var detailedApplies []model.QuitClubToUser
	for _, apply := range applies {
		var user model.User
		if err := DB.Where("uid = ?", apply.UserID).First(&user).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息失败!")
			return
		}

		var quit_apply model.QuitClub
		if err := DB.Where("id = ?", apply.Apply_ID).First(&quit_apply).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询退社分表失败!")
			return
		}
		fmt.Println("quit_apply.Reason", quit_apply.Reason)
		fmt.Println("quiyapply", quit_apply)
		var club model.Club
		if err := DB.Where("id = ?", quit_apply.CID).First(&club).Error; err != nil {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团信息失败!")
			return
		}

		detailedApply := model.QuitClubToUser{
			ID:            apply.ID,
			ApplyID:       apply.Apply_ID,
			ApplyTime:     apply.ApplyTime,
			UID:           apply.UserID,
			UName:         user.Uname,
			CID:           club.Cid,
			CName:         club.Cname,
			Reason:        quit_apply.Reason,
			ApprovalState: apply.Approval_State,
		}

		detailedApplies = append(detailedApplies, detailedApply)
	}

	response.Success(ctx, gin.H{"qclubs": detailedApplies}, "退社申请获取成功!")
}

// 审批函数,使用事物进行回滚
func ApproveApply(ctx *gin.Context) {
	db := common.GetDB()
	permission := ctx.PostForm("permission")
	action := ctx.PostForm("action")
	kind := ctx.PostForm("kind")
	id := ctx.PostForm("id")
	apply_id := ctx.PostForm("apply_id")
	uidStr := ctx.PostForm("uid")
	cidStr := ctx.PostForm("cid")
	aidStr := ctx.PostForm("aid")
	approverStr := ctx.PostForm("approver")
	cname := ctx.PostForm("cname")
	aname := ctx.PostForm("aname")
	// 仅在不为空的情况下进行转换
	var uid, aid, cid, approver int
	var err error

	if uidStr != "undefined" {
		uid, err = strconv.Atoi(uidStr)
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 422, nil, "用户ID转换失败！")
			return
		}
	}

	if aidStr != "undefined" {
		aid, err = strconv.Atoi(aidStr)
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 422, nil, "活动ID转换失败！")
			return
		}
	}

	if cidStr != "undefined" {
		cid, err = strconv.Atoi(cidStr)
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 422, nil, "社团ID转换失败！")
			return
		}
	}
	if approverStr != "undefined" {
		approver, err = strconv.Atoi(approverStr)
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 422, nil, "审批人ID转换失败！")
			return
		}
	}

	remark := ctx.PostForm("remark")
	time_str := ctx.PostForm("approval_time")
	approval_time, err := time.Parse("2006-01-02 15:04:05", time_str)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format"})
		return
	}

	// 开始事务
	tx := db.Begin()
	if tx.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "事务启动失败!")
		return
	}
	var apply model.Apply
	approvalState := 0
	switch permission {
	case "1":
		if action == "approve" {
			approvalState = 1
		} else if action == "reject" {
			approvalState = 2
		}
		result := tx.Model(&apply).Where("id = ?", id).Updates(map[string]interface{}{
			"Approval_State": approvalState,
			"ApprovalDate1":  approval_time,
			"Remark1":        remark,
		})
		if result.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新总表入社申请失败!")
			return
		}
	case "2":
		if action == "approve" {
			approvalState = 3
		} else if action == "reject" {
			approvalState = 4
		}
		result := tx.Model(&apply).Where("id = ?", id).Updates(map[string]interface{}{
			"Approval_State": approvalState,
			"ApprovalDate2":  approval_time,
			"Remark1":        remark,
		})
		if result.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新总表入社申请失败!")
			return
		}
	case "3":
		if action == "approve" {
			approvalState = 5
		} else if action == "reject" {
			approvalState = 6
		}
		result := tx.Model(&apply).Where("id = ?", id).Updates(map[string]interface{}{
			"Approval_State": approvalState,
			"ApprovalDate3":  approval_time,
			"Remark2":        remark,
		})
		if result.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新总表入社申请失败!")
			return
		}
	default:
		tx.Rollback()
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid permission value"})
		return
	}

	// 更新分表
	switch kind {
	case "0": // 入社申请
		pState := 1
		lid := 1
		if approvalState != 1 {
			pState = 2
			lid = 2
		}
		//0.2更新入社申请表
		var clubPermission model.ClubPermission
		result1 := tx.Model(&clubPermission).Where("id = ?", apply_id).Updates(model.ClubPermission{
			PState: pState,
			Return: remark,
		})
		if result1.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新入社申请表失败!")
			return
		}
		//0.3入社通过更新社团成员表
		if pState == 1 {
			club_user := model.UserClub{
				UID:        uid,
				Cid:        cid,
				JoinTime:   approval_time.Truncate(24 * time.Hour),
				Permission: 0,
			}
			if err := tx.Table("user_clubs").Create(&club_user).Error; err != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新社团用户表失败!")
				return
			}
		}
		//0.4更新消息发送表
		msg_sender := model.MsgSender{
			Type:  0,
			SID:   cid,
			SName: cname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", cid, 0).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//0.5发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}
	case "1": // 加入活动申请
		pState := 1
		lid := 3
		if approvalState != 1 {
			pState = 2
			lid = 4
		}
		//1.2更新活动申请分表
		var activityApply model.ActivityApply
		result1 := tx.Model(&activityApply).Where("id = ?", apply_id).Updates(map[string]interface{}{
			"result": pState,
			"remark": remark,
		})
		if result1.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新活动申请表失败!")
			return
		}
		if pState == 1 {
			//1.3更新活动用户表
			activity_user := model.ActivityUser{
				UID:    uid,
				AID:    aid,
				Status: 0,
			}
			fmt.Println("uid:", uid)
			fmt.Println("aid:", aid)
			if err := tx.Table("activity_users").Create(&activity_user).Error; err != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新活动用户表失败!")
				return
			}
		}
		//1.4更新消息发送表
		msg_sender := model.MsgSender{
			Type:  1,
			SID:   aid,
			SName: aname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", aid, 1).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//1.5发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}
	case "2": // 年检申请
		updates := map[string]interface{}{}
		switch permission {
		case "2":
			updates["remark1"] = remark
		case "3":
			updates["remark2"] = remark
		}
		if approvalState >= 4 && approvalState <= 6 {
			state := 1
			if approvalState != 5 {
				state = 2
			}
			updates["state"] = state
		}
		lid := 5                //进度更新
		if approvalState != 3 { //有结果
			lid = 6
		}
		//2.2更新年检申请分表
		if approvalState >= 4 && approvalState <= 6 || remark != "" {
			result := tx.Table("apply_as").Where("id = ?", apply_id).Updates(updates)
			if result.Error != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新年检申请表失败!")
				return
			}
		}
		//2.3更新消息发送者表
		msg_sender := model.MsgSender{
			Type:  2,
			SID:   cid,
			SName: cname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", cid, 2).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//2.4发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}

	case "3": // 评优申请
		updates := map[string]interface{}{}
		switch permission {
		case "2":
			updates["remark1"] = remark
		case "3":
			updates["remark2"] = remark
		}
		if approvalState >= 4 && approvalState <= 6 {
			state := 1
			if approvalState != 5 {
				state = 2
			}
			updates["state"] = state
		}
		lid := 5                //进度更新
		if approvalState != 3 { //有结果
			lid = 8
		}
		//3.2更新评优申请表
		if approvalState >= 4 && approvalState <= 6 || remark != "" {
			result := tx.Table("apply_ce").Where("id = ?", apply_id).Updates(updates)
			if result.Error != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新申请表失败!")
				return
			}
		}
		//3.3更新消息发送者表
		msg_sender := model.MsgSender{
			Type:  3,
			SID:   aid,
			SName: aname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", aid, 3).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//3.4发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}

	case "4": // 创社
		updates := map[string]interface{}{}
		switch permission {
		case "2":
			updates["Remark1"] = remark
		case "3":
			updates["Remark2"] = remark
		}
		if approvalState >= 4 && approvalState <= 6 {
			state := 1
			if approvalState != 5 {
				state = 2
			}
			updates["state"] = state
		}
		lid := 5                //进度更新
		if approvalState == 5 { //有结果
			lid = 9
		} else if approvalState != 3 {
			lid = 10
		}
		//4.2更新创建社团分表
		if approvalState >= 4 && approvalState <= 6 || remark != "" {
			result1 := tx.Table("apply_createclub").Where("id = ?", apply_id).Updates(updates)
			if result1.Error != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新创建社团申请表失败!")
				return
			}
		}
		//4.3更新社团用户表
		if approvalState == 5 {
			fmt.Println("approval_time.Truncate(24 * time.Hour),", approval_time.Truncate(24*time.Hour))
			club_user := model.UserClub{
				UID:        uid,
				Cid:        cid,
				JoinTime:   approval_time.Truncate(24 * time.Hour),
				Permission: 1,
			}
			if err := tx.Create(&club_user).Error; err != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新社团用户表失败!")
				return
			}
			//为社团设置默认主图
			clubimage := model.CImage{
				Cid:  cid,
				Main: 1,
				Path: "https://xybt-1326728101.cos.ap-guangzhou.myqcloud.com/1_1720294375931.jpg",
			}
			if err1 := tx.Create(&clubimage).Error; err1 != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "设置社团封面表失败失败!")
				return
			}
		}
		//4.4更新消息发送者表
		msg_sender := model.MsgSender{
			Type:  4,
			SID:   cid,
			SName: cname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", cid, 4).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//4.5发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}
	case "5": // 举办活动
		updates := map[string]interface{}{}
		switch permission {
		case "2":
			updates["Remark1"] = remark
		case "3":
			updates["Remark2"] = remark
		}
		lid := 5                //进度更新
		if approvalState == 5 { //有结果
			lid = 11
		} else if approvalState != 3 {
			lid = 12
		}
		//5.2更新举办活动分表
		if approvalState >= 4 && approvalState <= 6 {
			state := 1
			if approvalState != 5 {
				state = 2
			}
			updates["state"] = state
		}
		if approvalState >= 4 && approvalState <= 6 || remark != "" {
			result1 := tx.Table("activity_creates").Where("id = ?", apply_id).Updates(updates)
			if result1.Error != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新活动创建申请表失败!")
				return
			}
		}
		//5.3更新活动用户表
		if approvalState == 5 {
			activity_user := model.ActivityUser{
				UID:    uid,
				AID:    aid,
				Status: 1,
			}
			if err := tx.Table("activity_users").Create(&activity_user).Error; err != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新活动用户表失败!")
				return
			}
		}
		//5.4更新消息发送者表
		msg_sender := model.MsgSender{
			Type:  5,
			SID:   aid,
			SName: aname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", aid, 5).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//5.5发送消息
		message := model.Message{
			Sid:          msg_sender.ID,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Approver:     approver,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}
		//5.6查询举办活动的社团的未退社用户
		var userclub []model.UserClub
		if err := tx.Table("user_clubs").Select("UID").Where("Cid = ?and QTime IS NULL and UID!=", cid, uid).Find(&userclub).Error; err != nil {
			// 查询失败时回滚事务
			tx.Rollback()
			fmt.Println("查询 user_clubs 表时发生错误:", err)
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询社团用户表失败")
			return
		}
		//5.7查询msg_sender表用于通知社团活动
		var msgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("type = ? AND sid = ?", 9, cid).First(&msgSender).Error; err != nil {
			if gorm.ErrRecordNotFound == err {
				// 不存在记录，插入新的记录
				newMsgSender := model.MsgSender{
					Type:  9,
					SID:   cid,
					SName: cname,
				}
				if err := tx.Table("msg_sender").Create(&newMsgSender).Error; err != nil {
					// 插入失败时回滚事务
					tx.Rollback()
					fmt.Println("插入 msg_sender 表时发生错误:", err)
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "插入消息发送者失败")
					return
				}
				msgSender = newMsgSender
			} else {
				// 查询失败时回滚事务
				tx.Rollback()
				fmt.Println("查询 msg_sender 表时发生错误:", err)
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者失败")
				return
			}
		}
		//5.8通知用户社团活动信息
		for _, user := range userclub {
			// 更新消息表 msg
			newMsg := model.Message{
				Sid:      msgSender.ID,
				Rid:      user.UID,
				Lid:      17,
				Approver: approver,
				Mtime:    approval_time,
			}
			if err := tx.Table("msg").Create(&newMsg).Error; err != nil {
				// 插入失败时回滚事务
				tx.Rollback()
				fmt.Println("插入 msg 表时发生错误:", err)
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "插入消息失败")
				return
			}
		}

	case "6": // 退社申请
		pState := 1
		lid := 13
		if approvalState != 1 {
			pState = 2
			lid = 14
		}
		//6.2更新退社申请表
		var quitclub model.QuitClub
		result1 := tx.Model(&quitclub).Where("id = ?", apply_id).Updates(model.QuitClub{
			State:  pState,
			Remark: remark,
		})
		if result1.Error != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新退社申请表失败!")
			return
		}
		//6.3更新社团成员表
		if pState == 1 {
			quitTime := approval_time.Truncate(24 * time.Hour)
			result2 := tx.Model(&model.UserClub{}).Where("UID = ? and Cid=?", uid, cid).Updates(model.UserClub{
				QuitTime: &quitTime,
				//QuitTime: approval_time.Truncate(24 * time.Hour),
			})
			if result2.Error != nil {
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新社团成员表失败!")
				return
			}
		}
		//6.4更新消息发送者表
		msg_sender := model.MsgSender{
			Type:  6,
			SID:   cid,
			SName: cname,
		}
		// 首先检查数据库中是否存在该记录
		var existingMsgSender model.MsgSender
		if err := tx.Table("msg_sender").Where("sid = ? AND type = ?", cid, 6).First(&existingMsgSender).Error; err != nil {
			// 如果记录不存在则创建新记录
			if gorm.IsRecordNotFoundError(err) {
				if err := tx.Table("msg_sender").Create(&msg_sender).Error; err != nil {
					tx.Rollback()
					response.Response(ctx, http.StatusInternalServerError, 500, nil, "更新消息发送者表失败!")
					return
				}
			} else {
				// 其他错误处理
				tx.Rollback()
				response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询消息发送者表失败!")
				return
			}
		} else {
			// 记录存在，加载现有记录
			msg_sender = existingMsgSender
		}
		//6.5发送消息
		message := model.Message{
			Sid:          cid,
			Rid:          uid,
			Lid:          lid,
			ExtraContent: remark,
			Mtime:        approval_time,
		}
		if err := tx.Table("msg").Create(&message).Error; err != nil {
			tx.Rollback()
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "发送消息失败!")
			return
		}
	default:
		tx.Rollback()
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid kind value"})
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "事务提交失败!")
		return
	}

	response.Success(ctx, gin.H{"msg": "审批成功!"}, "审批操作成功!")
}
